package pages;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import database.DBException;
import database.DBUtils;

import templates.Template;

/**
 * Servlet implementation class AddXSL
 */
public class AddXSL extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final String pageTitle = "Add XSL";
	private static final String templateName = "addXSL";
	private static final String typeTemplateName = "xsl_type_select";
	private static final String typeRowTemplateName = "xsl_type_option";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddXSL() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			Template template = new Template(templateName);

			template.addChange("error", LMUtils.getRequestAttribute(request,
					"error"));
			template.addChange("name", LMUtils.getRequestAttribute(request,
					"xslName"));
			XSLType xslType = (XSLType) request.getAttribute("xslType");
			template.addChange("type_select", getXSLTypes(xslType));
			template.addChange("content", LMUtils.getRequestAttribute(request,
					"content"));

			response.getWriter().print(
					template.createPage(pageTitle, LMUtils
							.getUserLogin(request)));

		} catch (Exception e) {
			ErrorPage.printErrorPage(e.getMessage(), request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String error = "";
		try {
			if (LMUtils.getRequestParameterValue(request, "submit") != null) {
				String xslName = LMUtils.getRequestParameterValueNotEmpty(
						request, "name");
				String xslType = LMUtils.getRequestParameterValueNotEmpty(
						request, "type");
				String content = LMUtils.getRequestParameterValueNotEmpty(
						request, "content");

				LMUtils.setRequestAttribute(request, "xslName", xslName);
				request.setAttribute("xslType", XSLType.valueOf(xslType));
				LMUtils.setRequestAttribute(request, "content", content);
				insertXSL(xslName, xslType, content);
				error = "Done!";
			}
		} catch (MissingParameterException e) {
			error = "All the fields are required";
		} catch (Exception e) {
			error = e.getMessage();
		}
		LMUtils.setRequestAttribute(request, "error", error);
		doGet(request, response);
	}

	/**
	 * Generates combo-box containing all XSLTypes
	 * 
	 * @param selectedType
	 * @return String with combo-box
	 * @throws InternalErrorException
	 */
	private String getXSLTypes(XSLType selectedType)
			throws InternalErrorException {
		Template selectTemplate = new Template(typeTemplateName);
		Template optionTemplate = new Template(typeRowTemplateName);
		String options = "";
		for (XSLType option : XSLType.values()) {
			optionTemplate.addChange("name", option.toString());
			optionTemplate.addChange("value", option.toString());
			optionTemplate.addChange("selected",
					option.equals(selectedType) ? "selected=\"selected\"" : "");
			options += optionTemplate.applyChanges();
		}
		selectTemplate.addChange("xml_type_options", options);
		return selectTemplate.applyChanges();
	}

	/**
	 * Inserts new XSL into DB
	 * 
	 * @param xslName
	 * @param xslType
	 * @param content
	 * @throws InternalErrorException
	 * @throws DBException
	 */
	private void insertXSL(String xslName, String xslType, String content)
			throws InternalErrorException, DBException {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			String xslsTableName = LMUtils.getContextParameterValue(
					getServletContext(), "db.XSLsTableName");
			String query = "INSERT INTO `" + xslsTableName + "` (" + "`name` ,"
					+ "`xmlType` ," + "`content`" + ") VALUES (?, ?, ?)"
					+ " ON DUPLICATE KEY UPDATE `content` = ?;";
			conn = DBUtils.getConnection();
			stmt = conn.prepareStatement(query);
			stmt.setString(1, xslName);
			stmt.setString(2, xslType.toString());
			stmt.setString(3, content);
			stmt.setString(4, content);
			stmt.execute();
		} catch (SQLException e) {
			throw new DBException("Can't insert XSL: " + e.getMessage(), e);
		} finally {
			DBUtils.close(rs);
			DBUtils.close(stmt);
			DBUtils.close(conn);
		}
	}
}
